<?php
// +----------------------------------------------------------------------
// | Fanwe 多语商城建站系统 (Build on ThinkPHP)
// +----------------------------------------------------------------------
// | Copyright (c) 2009 http://www.fanwe.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 云淡风轻(97139915@qq.com)
// +----------------------------------------------------------------------
//基础action
class FanweAction extends Action {

	public function __construct ()
	{
		//checkAuthorization();
		$this->checkInstall();
		$this->init_module();
		filter_request($_REQUEST);
		//重新处理后台的语言加载机制，后台语言环境配置于config.php文件
		$langSet = C('DEFAULT_LANG');
		// 定义当前语言
		define('FANWE_LANG_SET', strtolower($langSet));

		// 读取项目公共语言包
		if (is_file(LANG_PATH . $langSet . '/common.php'))
			L(include LANG_PATH . $langSet . '/common.php');

		$group = '';
		// 读取当前分组公共语言包
		if (defined('GROUP_NAME'))
		{
			$group = GROUP_NAME . C('TMPL_FILE_DEPR');
			if (is_file(LANG_PATH . $langSet . '/' . $group . 'lang.php'))
				L(include LANG_PATH . $langSet . '/' . $group . 'lang.php');
		}
		// 读取当前模块语言包
		if (is_file(LANG_PATH . $langSet . '/' . $group . MODULE_NAME . '.php'))
			L(include LANG_PATH . $langSet . '/' . $group . MODULE_NAME . '.php');
			//处理end
		parent::__construct();
		$langItem = D("LangConf")->where("lang_name='" . C('DEFAULT_LANG') . "'")->find();
		if (! $langItem)
		{
			$langItem = D("LangConf")->where("lang_name='" . fanweC('DEFAULT_LANG') . "'")->find();
		}
		define('SHOP_NAME', $langItem['shop_name']);
		$this->assign('SHOP_NAME', SHOP_NAME);
		$this->assign('HTTP_HOST', "http://".$_SERVER["HTTP_HOST"]);
		$default_lang_id = $langItem["id"];
		define("DEFAULT_LANG_ID", $default_lang_id);
		$this->assign("DEFAULT_LANG_ID", DEFAULT_LANG_ID);
	}

	public function getRealPath ()
	{
		return getcwd();
	}

	//用于日志的记录
	protected function saveLog ($result = '1', $dataId = 0, $msg = '')
	{
		if (fanweC("APP_LOG"))
		{
			$log_app = C("LOG_APP");
			$log_module = MODULE_NAME;
			$log_action = $_REQUEST[C("VAR_ACTION")];
			if (in_array($log_action, $log_app[$log_module]))
			{
				$logData['log_module'] = $log_module;
				$logData['log_action'] = $log_action;
				if (! $dataId)
				{
					$pk = M(MODULE_NAME)->getPk();
					$dataId = intval($_REQUEST[$pk]);
				}
				$logData['data_id'] = $dataId;
				$logData['log_time'] = gmtTime();
				$logData['adm_id'] = intval($_SESSION[C("USER_AUTH_KEY")]);
				$logData['ip'] = get_client_ip();
				$logData['log_result'] = $result;
				$logData['log_msg'] = $msg;
				D("Log")->add($logData);
			}
		}
	}

	//图片上传的基本方法。未完成。待配置扩展......
	/**
	 * 上传图片的通公基础方法
	 *
	 * @param integer $water  0:不加水印 1:打印水印
	 * @param string $dir  上传的文件夹
	 * @param integer $uploadType 0:普通图片 1:产品图片
	 * @return array
	 */
	protected function uploadFile ($water = 0, $dir = 'attachment', $uploadType = 0)
	{
		$water_mark = fanweC("WATER_IMAGE");
        if(empty($water_mark))
            $water = 0;

		$water_mark = $this->getRealPath() . fanweC("WATER_IMAGE"); //配置于config

        if($water == 1 && !file_exists($water_mark))
            $water = 0;

		$alpha = fanweC("WATER_ALPHA");
		$place = fanweC("WATER_POSITION");
		$upload = new UploadFile();
		//设置上传文件大小
		$upload->maxSize = fanweC('MAX_UPLOAD'); /* 配置于config */
		//设置上传文件类型
		$upload->allowExts = explode(',', fanweC('ALLOW_UPLOAD_EXTS')); /* 配置于config */
		if ($uploadType)
			$save_rec_Path = "/public/upload/" . $dir . "/origin/" . toDate(gmtTime(), 'Ym') . "/"; //上传产品时先存放原图
		else
			$save_rec_Path = "/public/upload/" . $dir . "/" . toDate(gmtTime(), 'Ym') . "/"; //上传至服务器的相对路径
		$savePath = $this->getRealPath() . $save_rec_Path; //绝对路径
		if (! is_dir($savePath))
		{
			mk_dir($savePath);
		}
		$upload->saveRule = "uniqid"; //唯一
		$upload->savePath = $savePath;
		if ($upload->upload())
		{
			$uploadList = $upload->getUploadFileInfo();
			foreach ($uploadList as $k => $fileItem)
			{
				if ($uploadType) //产品上传时
				{
					$big_width = fanweC("BIG_WIDTH");
					$big_height = fanweC("BIG_HEIGHT");
					$small_width = fanweC("SMALL_WIDTH");
					$small_height = fanweC("SMALL_HEIGHT");
					$file_name = $fileItem['savepath'] . $fileItem['savename']; //上图原图的地址
					//开始缩放处理产品大图
					$big_save_path = str_replace("origin", "big", $savePath); //大图存放图径
					if (! is_dir($big_save_path))
					{
						mk_dir($big_save_path);
					}
					$big_file_name = str_replace("origin", "big", $file_name);
					if (fanweC("AUTO_GEN_IMAGE") == 1)
						Image::thumb($file_name, $big_file_name, '', $big_width, $big_height);
					else
						@copy($file_name, $big_file_name);
					if ($water && file_exists($water_mark) && fanweC("AUTO_GEN_IMAGE") == 1)
					{
						Image::water($big_file_name, $water_mark, $big_file_name, $alpha, $place);
					}
					//开始缩放处理产品小图
					$small_save_path = str_replace("origin", "small", $savePath); //小图存放图径
					if (! is_dir($small_save_path))
					{
						mk_dir($small_save_path);
					}
					$small_file_name = str_replace("origin", "small", $file_name);
					Image::thumb($file_name, $small_file_name, '', $small_width, $small_height);
					$big_save_rec_Path = str_replace("origin", "big", $save_rec_Path); //大图存放的相对路径
					$small_save_rec_Path = str_replace("origin", "small", $save_rec_Path); //大图存放的相对路径
					$uploadList[$k]['recpath'] = $save_rec_Path;
					$uploadList[$k]['bigrecpath'] = $big_save_rec_Path;
					$uploadList[$k]['smallrecpath'] = $small_save_rec_Path;
				}
				else
				{
					$uploadList[$k]['recpath'] = $save_rec_Path;
					$file_name = $fileItem['savepath'] . $fileItem['savename'];
					if ($water && file_exists($water_mark))
					{
						Image::water($file_name, $water_mark, $file_name, $alpha, $place);
					}
				}
			}
			return $uploadList;
		}
		else
		{
			return false;
		}
	}

	private function checkInstall ()
	{
		if (! file_exists($this->getRealPath() . "/public/install.lock"))
		{
			Dir::delDir($this->getRealPath() . "/admin/Runtime/");
			Dir::delDir($this->getRealPath() . "/app/Runtime/");
			Dir::delDir($this->getRealPath() . "/install/Runtime/");
			@mkdir($this->getRealPath() . "/admin/Runtime/", 0777);
			@mkdir($this->getRealPath() . "/app/Runtime/", 0777);
			@mkdir($this->getRealPath() . "/install/Runtime/", 0777);
			header('Location:' . __ROOT__ . '/install.php');
			exit();
		}
	}

	//同步数据库中的Module
	private function init_module ()
	{
		$arr = Dir::getList($this->getRealPath() . "/admin/Lib/Action/");
		$modules = M("RoleNode")->where("auth_type = 1")->findAll();
		$exists_modules = array();
		foreach ($arr as $k => $v)
		{
			if ($v != '.' && $v != '..')
			{
				$module = str_ireplace("Action.class.php", "", $v);
				if ($module != $v && $module != 'Fanwe' && $module != 'Common' && $module != 'Public')
				{
					if (M("RoleNode")->where("module='" . $module . "' and action=''")->count() == 0)
					{
						//增加该模块授权
						$module_data['status'] = 1;
						$module_data['module'] = $module;
						$module_data['module_name'] = $module;
						$module_data['auth_type'] = 1;
						M("RoleNode")->add($module_data);
					}
					array_push($exists_modules, $module);
				}
			}
		}
		//删除多余的module
		M("RoleNode")->where(array("module" => array("not in" , $exists_modules) , "action" => ''))->delete();
	}
}
?>